/*
 * @Author: youngqj youngqj@126.com
 * @Date: 2024-10-23 20:01:59
 * @LastEditors: youngqj youngqj@126.com
 * @LastEditTime: 2024-11-01 19:35:00
 * @FilePath: /go/mallSystem/pkg/utils/systemInfo.go
 * @Description: 关于程序获得系统相关的比如内存占用情况 等。
 *
 * Copyright © Zhejiang Xiaoqu Information Technology Co., Ltd, All Rights Reserved.
 */
package utils

import (
	"fmt"
	"os"
	"path/filepath"
	"runtime"

	"github.com/shirou/gopsutil/v4/disk"
)

func convertBytes(bytes uint64) string {
	const (
		KB = 1024
		MB = KB * 1024
		GB = MB * 1024
	)

	switch {
	case bytes >= GB:
		return fmt.Sprintf("%.2f GB", float64(bytes)/float64(GB))
	case bytes >= MB:
		return fmt.Sprintf("%.2f MB", float64(bytes)/float64(MB))
	case bytes >= KB:
		return fmt.Sprintf("%.2f KB", float64(bytes)/float64(KB))
	default:
		return fmt.Sprintf("%d B", bytes)
	}
}

func GetMemoryUsage() string {
	var memStats runtime.MemStats
	runtime.ReadMemStats(&memStats)

	fmt.Printf("Memory Usage:\n")
	fmt.Printf("Alloc: %v\n", convertBytes(memStats.Alloc))
	fmt.Printf("TotalAlloc: %v\n", convertBytes(memStats.TotalAlloc))
	fmt.Printf("Sys: %v\n", convertBytes(memStats.Sys))
	fmt.Printf("NumGC: %v\n", memStats.NumGC)

	returnStr := fmt.Sprintf("当前占内存： %v ,垃圾回收次数： %v 次", convertBytes(memStats.Alloc), memStats.NumGC)
	return returnStr

}
func GetUserInfoetProgramPath() {
	exePath, err := os.Executable()
	if err != nil {
		fmt.Println("Error getting executable path:", err)
		return
	}
	absPath, _ := filepath.Abs(exePath)
	fmt.Printf("Program Path: %s\n", absPath)
}

func GetDiskUsage() string {
	usage, _ := disk.Usage("/")
	result := fmt.Sprintf("磁盘使用情况: 总共: %v GB, 可用: %v GB, 已用: %v GB, 占比: %.2f%%",
		usage.Total/1024/1024/1024, usage.Free/1024/1024/1024, usage.Used/1024/1024/1024, usage.UsedPercent)
	return result
}
